<template>
  <div>
    <TitleSecondary title="子阶段" @change="handleChangeIcon" />
    <ButtonGroup
      :options="buttons"
      class="button-container"
      @click="handleButtonClick"
    />
    <p-table
      class="table-container"
      :custom-header-row="customHeaderRowMinxin"
      table-layout="auto"
      row-key="id"
      :columns="columns"
      bordered
      :scroll="{ x: '100%' }"
      :pagination="false"
      :data-source="dataSource"
      :row-selection="rowSelectionMixin"
      @change="handleTableChange"
    >
      <template slot="stage" slot-scope="text, record">
        <span v-if="!(record.id + '').includes('dai')">
          {{ statusOptions[text] }}
        </span>
        <SelectDefault
          v-else
          v-model="record.stage"
          style="width: 13vw"
          :has-all="false"
          code="business_sub_stage_node"
        />
      </template>
      <template slot="processStatus" slot-scope="text, record">
        <span v-if="!(record.id + '').includes('dai')">
          {{ stateOptions[text] }}
        </span>
        <p-select v-else v-model="record.processStatus" style="width: 7vw">
          <p-select-option :key="0" :value="0">未启动</p-select-option>
          <p-select-option :key="1" :value="1">进行中</p-select-option>
          <p-select-option :key="2" :value="2">已完成</p-select-option>
        </p-select>
      </template>
      <template slot="startTime" slot-scope="text, record, index">
        <span v-if="!(record.id + '').includes('dai')">{{ text }}</span>
        <p-date-picker
          v-else
          v-model="record.startTime"
          :picker-options="pickerOptions1(record)"
          placeholder="请选择时间"
          value-format="YYYY-MM-DD HH:mm:ss"
          @change="handleInputChange($event, text, record, index, 'startTime')"
        />
      </template>
      <template slot="endTime" slot-scope="text, record, index">
        <span v-if="!(record.id + '').includes('dai')">{{ text }}</span>
        <p-date-picker
          v-else
          v-model="record.endTime"
          :picker-options="pickerOptions1(record)"
          placeholder="请选择时间"
          value-format="YYYY-MM-DD HH:mm:ss"
          @change="handleInputChange($event, text, record, index, 'endTime')"
        />
      </template>
      <template slot="currUserName" slot-scope="text, record, index">
        <span v-if="!(record.id + '').includes('dai')">{{ text }}</span>
        <div v-else>
          <p-icon type="user" />
          <SelectSearchPeople
            :value="text"
            style="width: 13vw"
            value-key="handleUser"
            @change="
              handleInputChange($event, text, record, index, 'currUserName')
            "
          />
        </div>
      </template>
    </p-table>
  </div>
</template>

<script>
import mixinTable from '@/mixins/mixin-table.js';
import {
  saveBatchOppySubStage,
  postSubStagedelete,
  postSubStagelist,
} from '@/api/business';
let index = 0;
const createDefaultItem = () => ({
  id: 'dai' + index++,
  stage: '',
  processStatus: '',
  currUserId: '',
  currUserName: [],
  principal: [],
  startTime: '',
  endTime: '',
});
export default {
  mixins: [mixinTable],
  props: {
    buttons: {
      type: [Array],
      default: () => [
        {
          key: 'add',
          type: 'primary',
          label: '新增',
        },
        {
          key: 'save',
          label: '保存',
        },
        {
          key: 'delete',
          label: '删除',
          icon: 'delete',
        },
      ],
    },
    opportunityId: {
      type: String,
      default: undefined,
    },
    dataSource: {
      type: Array,
      default: () => [],
    },
    columns: {
      type: [Array],
      default: () => [
        {
          align: 'center',
          title: '序号',
          width: 60,
          customRender(t, r, index) {
            return parseInt(index) + 1;
          },
        },
        {
          align: 'center',
          title: '子阶段',
          dataIndex: 'stage',
          required: true,
          scopedSlots: { customRender: 'stage' },
        },
        {
          align: 'center',
          title: '状态',
          dataIndex: 'processStatus',
          required: true,
          scopedSlots: { customRender: 'processStatus' },
        },
        {
          align: 'center',
          title: '开始时间',
          dataIndex: 'startTime',
          required: true,
          scopedSlots: { customRender: 'startTime' },
        },
        {
          align: 'center',
          title: '完成时间',
          dataIndex: 'endTime',
          required: true,
          scopedSlots: { customRender: 'endTime' },
        },
        {
          align: 'center',
          title: '负责人',
          dataIndex: 'currUserName',
          required: true,
          scopedSlots: { customRender: 'currUserName' },
        },
      ],
    },
  },
  data() {
    return {};
  },
  computed: {
    statusOptions() {
      return this.$store.state.dictionary.dict['business_sub_stage_node'] || {};
    },
    stateOptions() {
      return {
        0: '未启动',
        1: '进行中',
        2: '已完成',
      };
    },
  },
  watch: {},
  created() {
    this.getList();
  },
  methods: {
    pickerOptions1: {
      disabledTime: (time, record) => {
        if (record.endTime !== '') {
          return time.getTime() > new Date(record.endTime).getTime();
        }
      },
    },
    pickerOptions2: {
      disabledTime: (time, record) => {
        console.log('11111111111');
        return time.getTime() < new Date(record.startTime).getTime();
      },
    },
    handleButtonClick(key) {
      const fn = `${key}Callback`;
      this[fn] && this[fn]();
    },
    addCallback() {
      this.dataSource.push({ ...createDefaultItem() });
    },
    async getList(val) {
      const res = await postSubStagelist({
        bizType: '1',
        bizId: this.opportunityId,
      });
      if (val) {
        const filters = this.dataSource.filter(item => {
          return (item.id + '').includes('dai');
        });
        const data = res.data.data || [];
        this.dataSource = [...data, ...filters];
      } else {
        this.dataSource = res.data.data || [];
      }
    },
    async saveCallback() {
      const list = this.dataSource;
      const stageList = list.map(item => {
        return {
          stage: item.stage,
          processStatus: item.processStatus,
          startTime: item.startTime,
          endTime: item.endTime,
          currUserName: item.currUserName,
          currUserId: item.currUserId,
          // id: (item.id + '').includes('dai') ? undefined : item.id,
          bizType: '1',
          bizId: this.opportunityId,
        };
      });
      console.log(stageList, 'businessStageList');
      const res = await saveBatchOppySubStage(stageList);
      this.$message.success('保存成功');
      this.getList();
    },
    deleteCallback() {
      const ids = this.rowSelectionMixin.selectedRowKeys;
      if (!ids.length) {
        this.$message.error('请先选择数据！');
        return;
      }
      const idList = ids
        .filter(item => !(item + '').includes('dai'))
        .map(item => {
          return item;
        });
      this.$confirm(`该操作将删除 ${ids.length} 条数据，是否确认？`)
        .then(async () => {
          ids.forEach(id => {
            const index = this.dataSource.findIndex(item => item.id === id);
            this.dataSource.splice(index, 1);
          });
          this.rowSelectionMixin.selectedRowKeys = [];
          if (idList.length) {
            await postSubStagedelete(idList);
          }
          this.$message.success('删除成功');
          this.getList(true);
        })
        .catch(() => {
          // console.log('e: ', e);
        });
    },
    handleInputChange(e, text, record, index, key) {
      this.dataSource[index][key] = e;
      if (key === 'currUserName') {
        this.dataSource[index]['currUserId'] = e[0][0];
        this.dataSource[index]['currUserName'] = e[0][1];
      }
    },
  },
};
</script>

<style lang="less" scoped>
.item-container {
  display: flex;
  align-items: center;
}
.button-container {
  margin-bottom: 20px;
}
.table-container {
  margin-bottom: 40px;
}

/deep/ .poros-select-selection {
  border: none;
}
</style>
